package com.ls.hnks.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.ls.hnks.util.Result;
import com.ls.hnks.util.ResultCodeEnum;
import com.ls.hnks.common.constant.RoleConstant;
import com.ls.hnks.model.Customer;
import com.ls.hnks.model.Schedule;
import com.ls.hnks.model.User;
import com.ls.hnks.service.CustomerService;
import com.ls.hnks.service.ScheduleService;
import com.ls.hnks.service.UserService;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@Slf4j
@SaCheckLogin
@RestController
@RequestMapping("/schedule")
public class ScheduleController {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private UserService userService;

    @Autowired
    private CustomerService customerService;

    @RequestMapping("/details/{id}")
    public Result getDetails(@PathVariable String id) {
        return scheduleService.getDetails(id);
    }

    @RequestMapping("/pageByCustomer")
    public Result getPageByCustomerId(
            @ApiParam("客户ID") @RequestParam(value = "customerId") String customerId,
            @ApiParam("分页查询的页码数") @RequestParam(value = "page",defaultValue = "1")Integer page,
            @ApiParam("分页查询的页大小") @RequestParam(value = "size",defaultValue = "20")Integer size) {
        return scheduleService.getListByCustomerId(customerId,page,size);
    }

    @PostMapping("/save")
    public Result save(@RequestBody Schedule schedule) {
        log.info("日程信息 --- {}", JSON.toJSONString(schedule));
        return scheduleService.saveSchedule(schedule);
    }

    @RequestMapping("/byUser")
    public Result getListByUser(String userId,String date) {
        String selfId = StpUtil.getLoginId().toString();
        User self = userService.getById(selfId);
        User other = userService.getById(userId);
        if (other == null) {
            return Result.error(ResultCodeEnum.USER_NOT_FOUND);
        }
        // 管理员可以查看所有用户的行程,普通用户可以查看同组用户的行程
        if (self.getRight() != RoleConstant.ADMIN && !Objects.equals(self.getGroupid(), other.getGroupid())) {
            return Result.error(ResultCodeEnum.FORBIDDEN);
        }
        return scheduleService.getListByUserAndDate(userId, date);
    }

    @RequestMapping("/byCustomer")
    public Result getListByCustomer(String customerId,String date) {
        Customer customer = customerService.getById(customerId);
        if(customer == null){
            return Result.error(ResultCodeEnum.CUSTOMER_NOT_FOUND);
        }
        return scheduleService.getListByCustomerAndDate(customerId, date);
    }

    @PostMapping("/remove/{id}")
    public Result remove( @PathVariable String id){
        return scheduleService.removeSchedule(id);
    }
}
